#!/usr/bin/python
#
# Init script for varnish caching/load balancing server
#
# chkconfig: 123456 99 99
# description: ${name}
#
# Author: Benjamin Liles
#
#
### BEGIN INIT INFO
# Provides: ${name}
# Required-Start:
# Required-Stop:
# Default-Start:  123456
# Default-Stop:  123456
# Short-Description: ${name}
# Description: ${name}
### END INIT INFO

import sys, os, subprocess, signal

def start():
    if not os.path.exists('${pidfile}'):
        return subprocess.call(['${runner}'])
    print '%s already running' % (str(sys.argv[0]),) 
    return 1

def stop():
    if not os.path.exists('${pidfile}'):
        print '%s is not running' % (str(sys.argv[0]),)
        return 1
    
    try:
        pid = int(open('${pidfile}').read())
    except:
        print "No pid found?"
        return 1
    
    print "Pid: %s" % (str(pid),)
    try:
        os.kill(pid,signal.SIGTERM)
        print "Sent signal %s to pid %s" % (str(signal.SIGTERM),str(pid),)
        results = os.waitpid(pid, os.WUNTRACED)
        print "Waited for pid, %s" % (str(pid),)

        if os.WIFSTOPPED(results[1]):
            return 0
        return results[1]
    except Exception, e:
      print "Exception: %s" % (str(e),)
      os.remove('${pidfile}')
      return 0




_options = {
    'pidfile': '${pidfile}',
    'uid': ${uid},
    'gid': ${gid},
    'no_save': True,
    'originalname': '${name}',
    'chroot': None,
    'rundir': None,
    'nodaemon': None,
    'umask': None,
    'euid': None,
    'debug': None}



def logreopen():
    if not os.path.exists('${pidfile}'):
        print '%s is not running' % (str(sys.argv[0]),)
        return 1
    
    try:
        pid = int(open('${pidfile}').read())
    except:
        print "No pid found?"
        return 1
    
    try:
        os.kill(pid,signal.SIGHUP)
        print "Sent signal %s to pid %s" % (str(signal.SIGHUP),str(pid),)
        return 0
    except Exception, e:
      print "Exception: %s" % (str(e),)
      return 1

def status():
    """
    Print any relevant status info, and return a status code, an integer:

    0          program is running or service is OK
    1          program is dead and /var/run pid file exists
    2          program is dead and /var/lock lock file exists
    3          program is not running
    4          program or service status is unknown
    5-99      reserved for future LSB use
    100-149      reserved for distribution use
    150-199      reserved for application use
    200-254      reserved

    @see: http://dev.linux-foundation.org/betaspecs/booksets/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
    """
    if os.path.exists('${pidfile}'):
        print "STATUS: Ok"
        return 0
    
    print "STATUS: Not running"
    return 3

# Main program switchboard - wrap everything in a try block to
# ensure the right return code is sent to the shell, and keep things tidy.
#
# @TODO: need to raise custom exception instead of ValueError, and
#        handle other exceptions better.
#
# @TODO: put lock/unlock calls inside of start/stop?
if __name__ == '__main__':
    try:
        # if there's fewer than 2 options on the command line
        # (sys.argv[0] is the program name)
        if len(sys.argv) == 1:
            raise ValueError;  

        action = str(sys.argv[1]).strip().lower()
        
        if action == 'status':
            sys.exit(status())
        elif action == 'start':
            sys.exit(start())
        elif action == 'stop':
            sys.exit(stop())
        elif action == 'restart':
            if stop() == 0:
                sys.exit(start())
            sys.exit(1)
        elif action == 'logreopen':
            sys.exit(logreopen())
        else:
             print >> sys.stderr, "Usage: %s [start|stop|restart|status|logreopen]" % (sys.argv[0],)
    except (SystemExit):
        # calls to sys.exit() raise this error :(
        pass
    except:
        # all other exceptions get caught here
        extype, value = sys.exc_info()[:2]
        print >> sys.stderr, "ERROR: %s (%s)" % (extype, value)
        # return 1 for "general error"
        sys.exit(1)
